<?php
namespace app\index\controller;

use app\common\model\Exchange;
use app\lib\exception\BaseException;
use think\Controller;
use think\Db;

class Admin extends Controller
{
    /**
     * 核销订单
     * @return mixed
     */
    public function exchange()
    {
        $sign = input('sign');
        $exchange_id = input('exchange_id');
        $salt = config('common.code_salt');
        if ($password = input('password')) {
            //查找是哪家店铺ghfh
            $store = model('store')->where(['password' => $password])->find();
            if (!$store) {
                throw new BaseException(['msg'=>'核销密码有误,店铺不存在！']);
                exit();
            }
            //进行核销
            if ($sign !== md5($exchange_id . $salt)) {
                throw new BaseException(['msg'=>'签名异常，非法二维码！']);
            }
            $res = Db::table('__EXCHANGE__')->where('id=' . $exchange_id)->find();
            if (!$res) {
                throw new BaseException(['msg'=>'非法二维码！']);
            }
            if ($res['is_exchanged']) {
                throw new BaseException(['msg'=>'该券已经兑换过！']);
            }
            $time = time();
            if($time<$res['start_time'] || $time>$res['end_time']){
                throw new BaseException(['msg'=>'请在兑换时间内兑换！']);
            }
            $data = [
                'is_exchanged' => 1,
                'store_id' => $store->id,
                'store_name' => $store->name,
                'consume_time'=>$time,
                'consume_date'=>date('Y-n-j',$time),
            ];
            $res = Exchange::update($data,['id'=>$exchange_id]);
            if ($res) {
                throw new BaseException(['msg'=>'核销成功！']);
            } else {
                throw new BaseException(['msg'=>'核销失败！未知错误！']);
            }
        }
        $this->assign('sign',$sign);
        $this->assign('exchange_id',$exchange_id);
        return $this->fetch();
    }
}
